from app.libs.http_book import HTTP
from flask import current_app


class YuShuBook:
    per_page = 15
    isbn_url = 'https://jisuisbn.market.alicloudapi.com/isbn/query?isbn={}'
    keyword_url = 'https://jisuisbn.market.alicloudapi.com/isbn/search?title={}&pagenum={}'
    app_code = ('6a9e2d8e40e3472faea64eef7092bddc')
    headers = {"Authorization": "APPCODE " + app_code}

    def __init__(self):
        self.total = 0
        self.books = []

    def search_by_isbn(self, isbn):
        url = self.isbn_url.format(isbn)
        result = HTTP.get(url, headers=self.headers)
        self.__fill_single(result['result'])

    def __fill_single(self, data):
        if data:
            self.total = 1
            self.books.append(data)

    def __fill_collection(self, data):
        if data:
            self.total = data['total']
            self.books = data['list']

    def search_by_keyword(self, keyword, page=0):
        print(current_app.config['PER_PAGE'])
        url = self.keyword_url.format(keyword, page)
        result = HTTP.get(url, headers=self.headers)
        print(result)
        self.__fill_collection(result['result'])

    @property
    def first(self):
        return self.books[0] if self.total >= 1 else None
